import { Capacitor, WebPlugin } from '@capacitor/core';

import type { VideoPlayerPlugin } from './definitions';
import MobileDetect from 'mobile-detect';

export class VideoPlayerWeb extends WebPlugin implements VideoPlayerPlugin {
  async echo(options: { value: string }): Promise<{ value: string }> {
    console.log('ECHO', options);
    return options;
  }
  async play(options: {
    videos: { url: string; title: string; subs: { url: string; title: string }[] }[];
    defaultIndex: number;
  }): Promise<{ value: boolean }> {
    const md = new MobileDetect(window.navigator.userAgent);

    console.log('Platform: ', Capacitor.getPlatform());
    console.log('OS: ', md.os());
    console.log('Total Video: ', options.videos.length);
    console.log('Video to Play: ', options.defaultIndex);
    if (Capacitor.getPlatform() === 'electron') {
      (window as any).electron.ipc.invoke('playVideo', options.videos, options.defaultIndex);
    } else {
      console.warn(
        "This is not Electron Environment, use weburl to open the url by vlc, don't support to use subtitles and playlist!",
      );
      if (md.os() === "iOS") {
        window.open(`nplayer-${options.videos[options.defaultIndex].url}`, '_blank');
      } else {
        window.open(`vlc://${options.videos[options.defaultIndex].url}`, '_blank');
      }
    }
    return { value: true };
  }
}
